package com.yihaodian.index.meta.shard.impl;

import java.util.Collection;
import java.util.Iterator;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yihaodian.api.index.IndexDoc;
import com.yihaodian.cluster.ClusterState;
import com.yihaodian.index.meta.IndexMeta;
import com.yihaodian.index.meta.shard.Shard;
import com.yihaodian.index.meta.shard.ShardHandler;
import com.yihaodian.index.meta.shard.ShardId;

public class ModShardHandler implements ShardHandler {
	String field = null;

	JsonParser parser = new JsonParser();

	public ModShardHandler() {
	}

	public ModShardHandler(String field) {
		this.field = field;
	}

	public void setField(String field) {
		this.field = field;
	}

	@Override
	public ShardId shard(ClusterState cs, String indexName, IndexDoc object) {
		IndexMeta meta = cs.indexMetas().indexMeta(indexName);
		Collection<Shard> shards = meta.getShards();

		String key = object.getId();
		if (field != null) {
			JsonObject obj = (JsonObject) parser.parse(object.getJsonDoc());
			key = obj.get(field).getAsString();
		}

		int size = shards.size();
		int mod = key.hashCode() % size;

		Iterator<Shard> it = shards.iterator();

		Shard shard = null;
		int i = 0;
		while (it.hasNext()) {
			shard = it.next();
			if (i++ == mod)
				break;
		}

		ShardId id = shard.getShardId();

		if (object.equals("383d0b4bef5f3c5604a0f0e6dade5a2e"))
			System.out.println(id + " " + object);

		return id;
	}
}
